#ifndef DAV_MAIN_H
#define DAV_MAIN_H
//
#include "ui_dav_main.h"
#include "main.h"
#include "basedav.h"
#include "base_modul.h"
#include "qxml.h"
#include "main.h"
#include <QItemDelegate>
#include "gui_remove.h"
#include "basedav.h"
#include "networkdav.h"
#include "dav_get.h"
#include "davmove.h"
#include "gui_about.h"
#include <QSound>
#include <QSystemTrayIcon>
#include "gui_connection.h"
#include "gui_info.h"
//
/*  Save file as dav_main.h  */
/*  incomming class name Dav_Main */
//
#include <QPointer>

                          



class FileManager: public QObject, public Base_Modul
{
    Q_OBJECT
    
public: 
    
FileManager( QString name , bool dir , QString remotelocation , uint filetime , QString uniqueserverid ,  QWidget * parent)
{
 /* bool dir true / file false */
 p = parent;
 nam = name;
 relocwww = remotelocation;
 timefile = filetime;
 isdir = dir;
 getetag = uniqueserverid;
}

QString LocalMirrorFileOrDir()
{
    QString dirorfile =  QString(setter.value("MirrorDir").toString());
    dirorfile = dirorfile.append(relocwww);
    dirorfile = dirorfile.replace("//","/");
    
    return dirorfile;
}


uint HavingLocalCopy()
{   
    uint updates = 0;
        if (is_file(LocalMirrorFileOrDir())) {
                       QFileInfo milocal(LocalMirrorFileOrDir());
            QDateTime lastdate = milocal.lastModified();
            updates = lastdate.toTime_t();
        }
    return updates;
}

inline bool IsDir() const { return isdir; }
inline QString GetTit() const { return nam; }
inline QString GetTag() const { return getetag; }
inline QString Geturl() const { return relocwww; }
inline uint GetFileTimeRemote() const { return timefile; }
protected:
private:
    QWidget *p;
    bool isdir;
    uint timefile;
    QSettings setter;
    QString nam;
    QString getetag;
    QString namsmall;
    QString relocwww;
    QString qrsize;
signals:
  //////void GetRemoteTo(QString wre, QString dle);
  void GrabandOpen( QString remote , QString localfile );
  void OneGetAppend( QString remote , QString localfile );
  void OpenFileorDir( QUrl makeopen );
  void RemoteDirRm(QString wre);
  void RenameRemotedir(QString from , QString to );
  void MainReFresh();
  void GrabtoMirrorDir( QString remotedir , QString localpath );
public slots:
uint CreatedLocalTime()
{   
    uint updates = 0;
    QString dirsave =  QString(setter.value("MirrorDir").toString());
    if (!dirsave.endsWith("/")) {
        dirsave.append("/");
    }
    if (dirsave.size() > 2) {
       dirsave = dirsave.append(relocwww);
        if (is_file(dirsave)) {
                       QFileInfo milocal(dirsave);
            QDateTime lastdate = milocal.created();
            updates = lastdate.toTime_t();
        }
    }
    
    return updates;
}

void RemoveDirRecursive()
{   
    qDebug() << "#### emit RemoteDirRm ->" << Geturl();
    emit RemoteDirRm(Geturl());
}


void DownloadDirRecursive()
{   
    QString dirsave =  QString(setter.value("MirrorDir").toString());
    if (!dirsave.endsWith("/")) {
        dirsave.append("/");
    }
    emit GrabtoMirrorDir(Geturl(),dirsave);
}


    







void RenameFolder()
{   
    if (!relocwww.endsWith("/")) {
    return;
    }
    qDebug() << "#### relocwww ->" << relocwww;
    QString basefrom;
    QString tat = PeelEnding(relocwww);
    QStringList list_t = tat.split("/");
    int leveltarget = list_t.size();
    
    
    if (leveltarget == 1) {
    basefrom = "/";
    } else {
        basefrom.append("/");
        leveltarget = leveltarget - 1;
        for (int i = 0; i < leveltarget; ++i) {
            basefrom.append(list_t.at(i));
            basefrom.append("/");
       }
    }
    
    qDebug() << "#### basetoappend ->" << basefrom;
    QString oldname = list_t.at(list_t.size() - 1 );
    bool ok;
    QString newdirname = QInputDialog::getText(0, tr("Rename"),tr("New Name:"), QLineEdit::Normal,oldname, &ok);
     //////////qDebug() << "#### newdirname ->" << newdirname;
    if (ok && newdirname.size() > 0 && oldname != FileNameFix(newdirname)) {
       QString newdirpath = QString("%1%2/").arg(basefrom).arg(FileNameFix(newdirname));
        qDebug() << "#### from ->" << relocwww;
        qDebug() << "#### to ->" << newdirpath;
        emit RenameRemotedir(relocwww,newdirpath);
    }
}


void LocalOpen()
{   
    QString tipefilelocal = LocalMirrorFileOrDir();
    QUrl gettyurl(tipefilelocal);
    QString localfildir = gettyurl.toLocalFile();
    
    if (relocwww.endsWith("/")) {
        /* dir */
        QDir dira(localfildir);
        if ( dira.mkpath(localfildir) ) { } else {
        /* unable to make dir */
        }
        emit OpenFileorDir(gettyurl);
        return;
     } else {
         /* file */
         if (is_file(tipefilelocal)) {
             
            emit GrabandOpen(relocwww,tipefilelocal);
             
             
             return;
         } else {
             emit GrabandOpen(relocwww,tipefilelocal);
             return;
         }
         
     }
}

void GettoLocal()
{   
    if (!relocwww.endsWith("/")) {
    QString tipefilelocal = LocalMirrorFileOrDir();
    fwriteutf8(tipefilelocal,"");  /* make dir if not exist on mirror or reset file to zero  */
    qt_unlink(tipefilelocal);  /* remove file */
    emit OneGetAppend(relocwww,tipefilelocal);
    }
}


void MirrorSetting()
{   
    QString dirsave = QFileDialog::getExistingDirectory(0,tr("Select a dir Mirror to Webdav"),QString(setter.value("MirrorDir").toString()),QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
    if (dirsave.size() > 3) {
      setter.setValue("MirrorDir",dirsave);
    }
    emit MainReFresh();
}


};








class ItemDelegate: public QItemDelegate
{
public:
        ItemDelegate()
        {
        }
        
        QSize sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const 
        {
               int cooler = index.column();
               ///////////////qDebug() << "### colonna " << cooler;
               if (cooler == 0) {
                  return QSize(100,22); 
               } else {
                  return QSize(50,22);
               } 
        }  
};


class Gui_Connection;
class Dav_Main : public QMainWindow, public Ui::Dav_Main, public Base_Modul
{
     Q_OBJECT
//
public:	 
    static Dav_Main* self( QWidget* = 0 );
//
protected:	 
    void closeEvent( QCloseEvent* );
    
    
    void Load_Connector();
    void SideTree( QDomDocument xml , const QString DisplayPath );
//
private:
 Dav_Main( QWidget* = 0 );
 void setupTray();
 Gui_Info *gdownload;
 QTreeWidgetItem *StreItem;
 QTreeWidgetItem *BigStreItem;
 Gui_Connection *davconnection;
 QList<QTreeWidgetItem *> treefolder;
 QSettings setter;
 BaseDav *mod_dav_0;
 BaseDav *mod_dav_1;
 BaseDav *mod_dav_2;
 QStringList cleandirlist;
 QIcon IconMimeMarker( QString name );
 QIcon IconMime( QString name );
 QStringList OnCodafile;
 QStringList OnCodadir;
 void SendUpPutList( QStringList localfiles , QStringList localdirs );
 void ResetHeader();
 QSystemTrayIcon *mTray;
 bool ongrab;
 bool netopen;
 bool activedir;
 bool SendNewFile;
 bool activefile;
 QString DefaultDir;
 QString status;
 QString PendingToOpen;
 QString DummyRoot;
 QString remoteconnecturl;
 QString TargetDirBuild;
 QMenu *TContext;
 QMenu *T_dir_Context;
 QMenu *T_file_Context;
 QMenu *TRicon;
 static QPointer<Dav_Main> _self;
 QList<FileManager*> treefile;
 NetworkDav *dbdav;
 Gui_Remove  *gremove;
 QAction *actioncatdock;
 void OpenRemoteFile( const QString fileremote , const QString iddavunique );
signals:

public slots:
    void ReloadNewBuild();
    void ChancheDir( const QString dir );
    void BuildTree( QDomDocument xml , const QString DisplayPath );
    void ShowStatusBar(QString msg);
    void AppendSub( QTreeWidgetItem * treeniro , int coolnummer );
    void SideSubTree( QDomDocument xml , const QString DisplayPath );
    void BigTreeCD( QTreeWidgetItem * treeniro , int coolnummer );
    void dragEnterEvent(QDragEnterEvent *event);
    void dropEvent(QDropEvent *event);
    void NextList( QString DirReload );
    void AutoReload();
    void ReloadActualDir();
    void OpenDesktop( QUrl loc );
    void SetResetMain();
    void GlobalContext( const QPoint & pos  );
    void MakeNewFolder();
    /* on send disable button or other */
    void SetNetworkEnable();
    void SetNetworkDisable();
    void MainRenamedir(QString from , QString to );
    void AboutOpen();
    
    /* recursive download dir */
    void GetDirRecursive(QString remotepath ,QString localpath );

    /* delete action */
     void RemoveonMain( const  QString dir );
     void CdUponeLevel( QString dirups );
     void CdUpfromDefault();
     void TargetRebuildRoot( QString dir );
     void TargetPendigDir();
     void GrabFile( QString remote , QString local );
     void OneGetandOpen( QString remote , QString local );
     void PendingFile();
     void OpenMirrorLocal();
     void ConnectionReset();
     
     /* link */
     void  Link_A();
     void  Link_B();
     void  Link_C();
     void  DavRootUrl();
     
     /* tray icon */
     void slotTrayActivated(int reason);
     void slotToggleVisibility();

};
//
#endif // DAV_MAIN_H

